package com.crb.crm.manage.oos.baidu;

import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.BosObject;
import com.crb.crm.manage.enums.OssType;
import com.crb.crm.manage.oos.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * 百度上传下载工具类
 **/
@Slf4j
@Component
class BaiduUtil implements OSSUtil {

    @Resource
    private BaiduConfig baiduConfig;

    private BosClient getBosClient() {
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(baiduConfig.getAccessKey(), baiduConfig.getSecretKey()));
        config.setEndpoint(baiduConfig.getEndpoint());
        BosClient client = new BosClient(config);
        return client;
    }

    @Override
    public OssType support() {
        return OssType.OSS_BAIDU;
    }

    @Override
    public boolean upload(InputStream is, String key) {
        BosClient client = getBosClient();
        try {
            client.putObject(baiduConfig.getBucket(), key, is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.shutdown();
        }
        return true;
    }

    @Override
    public boolean delete(String key) {
        BosClient client = getBosClient();
        try {
            client.deleteObject(baiduConfig.getBucket(), key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.shutdown();
        }
        return true;
    }

    @Override
    public InputStream download(String key) {
        BosClient client = getBosClient();
        BosObject object = client.getObject(baiduConfig.getBucket(), key);
        return object.getObjectContent();
    }
}